package com.lzp.java.serialiable.jdk;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 9141734903409956161L;
    private int userId;
    private String userName;
    private transient String account;

    public User(int userId, String userName, String account) {
        this.userId = userId;
        this.userName = userName;
        this.account = account;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", account='" + account + '\'' +
                '}';
    }

    /**
     * 序列化操作
     *
     * @param oos
     * @throws IOException
     */
    private void writeObject(ObjectOutputStream oos) throws IOException {
        // 将JVM可以默认序列化的元素序列化
        oos.defaultWriteObject();
        // 自身实现transient修饰元素的序列化
        oos.writeObject(account);

        oos.writeInt(userId);
    }

    /**
     * 反序列化操作
     *
     * @param ois
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        // 将JVM可以默认反序列化的原始反序列化
        ois.defaultReadObject();
        // 自己完成transient修饰元素的反序列化
        this.account = (String) ois.readObject();
    }
}
